#!/usr/bin/perl

# File: backup.pl
# Author: Arvind Subramanian (somdev3)
# Language: Perl 5

use strict;
use DBI;
use Getopt::Long;
use Backup::Create;
use File::Path;

# Mysql Username Config
my $dbiUsername = "";
my $dbiPassword = "";
my $dbiHost = "";
my $dbiSocket = "";

# Backup information
my $backupFolder = "";

# Get command line input
my $customName;my $force = 0;
GetOptions('o:s'=>\$customName,
	'u=s'=>\$dbiUsername,
	'p=s'=>\$dbiPassword,
	'h=s'=>\$dbiHost,
	's:s'=>\$dbiSocket,
	'd=s'=>\$backupFolder,
	'f'=>\$force);

if ( !($dbiUsername && $dbiPassword && $dbiHost && $backupFolder) ){
	print STDERR ("You must supply your mysql username, password, host (-u, -p, -h) in addition to the location of the backups (-d).\n");
	exit;
}

#Get Local time
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);$year += 1900;$mon++;$mon = $mon > 9 ? "$mon" : "0".$mon;$mday = $mday > 9 ? "$mday" : "0".$mday;

#Make sure directory format is consistent
$backupFolder = dirFormat($backupFolder);
if ( !(-d $backupFolder) ) {
	mkpath($backupFolder);
}

#Connect to database, get list of databases
my $dbh = DBI->connect("DBI:mysql:information_schema;host=$dbiHost;socket=$dbiSocket;",$dbiUsername,$dbiPassword);
my $databases = $dbh->selectcol_arrayref("SHOW DATABASES;");

#my @databases = @$databases;
my @databases = ("mwiki","StudTest","som_it");
#Make directory to package up later $backupFolder/%Y%M%D/
my $dirname;
if ( $customName ) {
	$dirname = "$backupFolder/$customName";
} else {
	$dirname = "$backupFolder/$year$mon$mday";
}
mkdir($dirname);

my $backup = Backup::Create->new($dbiUsername,$dbiPassword,$dbiHost,$dbiSocket);

if ( -f "$dirname/backup.ini" && !$force ) {
	print "Backup already exists at $dirname... continue anyway? [y/n]: ";
	my $input = <STDIN>;
	if ( !($input =~ "y") ) {
		exit;
	}
}

# This creates an INI file showing directory structure
foreach(@databases) {
	$backup->add($_);
}
$backup->save($dirname);

#Subroutines, NO LIVE CODE BELOW
sub dirFormat {
	my ($string) = @_;
	$string =~ s/\/$//;
	return $string;
}
